package com.iqiao.platform.controller;

/**
 * Created by flt on 2017/10/31.
 */

import com.iqiao.common.exception.AuthenticationException;
import com.iqiao.common.exception.ResetException;
import com.iqiao.common.web.result.JsonResult;
import com.iqiao.common.web.result.ReturnCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handlerServerError(HttpServletRequest request, Exception ex) {
        logger.error("handlerServerError", ex);
        return new JsonResult(ReturnCode.ERROR, "服务器错误！");
    }

    @ResponseBody
    @ExceptionHandler(value = {ResetException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handlerRestError(HttpServletRequest request, ResetException ex) {
        logger.error("handlerRestError", ex);
        return ex.getJsonResult();
    }

    @ResponseBody
    @ExceptionHandler(value = {AuthenticationException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public JsonResult handlerRestError(HttpServletRequest request, AuthenticationException ex) {
        logger.error("handlerRestError", ex);
        return new JsonResult(ReturnCode.NOT_LOGIN, "请先登录！");
    }

    @ResponseBody
    @ExceptionHandler(value = {AccessDeniedException.class})
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public JsonResult handlerServerError(HttpServletRequest request, AccessDeniedException ex) {
        logger.error("handlerServerError", ex);
        return new JsonResult(ReturnCode.FORBIDDEN, "没有权限！");
    }

    @ResponseBody
    @ExceptionHandler(value = {InternalAuthenticationServiceException.class, UsernameNotFoundException.class, BadCredentialsException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult handlerAuthError(HttpServletRequest request, Exception ex) {
        logger.error("handlerAuthError", ex);
        return new JsonResult(ReturnCode.USER_USERNAME_PASSWORD_ERROR, "用户名密码错误！");
    }

}
